package com.ruoyi.common.encrypt;

import com.ruoyi.common.exception.base.BaseException;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

import java.security.NoSuchAlgorithmException;
import java.security.spec.InvalidKeySpecException;
import java.util.Map;

/**
 * 解密并或者结构体数据
 */

public class DecodeBody {

    /**
     * 公钥key
     */
    private static final String PUBLIC_KEY = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCdy-ekgmS9ffvC1cdXAWIFgeKOhezOjOziOf51okqStDxj4u_EkIjnFNkJ48cIlW8NlMbp9EezndD2yZEC-ozOUnHxLj2sRNrHBjZWm9-39k3dHEGVnWJ_1WSbQwzVTXe6HpJnDtO6kI7lU8qtresXg5wmHusb5dcYPMUi0R7RCQIDAQAB";

    /**
     * 私钥KEY
     */
    private static final String PRIVATE_KEY = "MIICdgIBADANBgkqhkiG9w0BAQEFAASCAmAwggJcAgEAAoGBAJ3L56SCZL19-8LVx1cBYgWB4o6F7M6M7OI5_nWiSpK0PGPi78SQiOcU2QnjxwiVbw2Uxun0R7Od0PbJkQL6jM5ScfEuPaxE2scGNlab37f2Td0cQZWdYn_VZJtDDNVNd7oekmcO07qQjuVTyq2t6xeDnCYe6xvl1xg8xSLRHtEJAgMBAAECgYB2DKa2bwp4rPidMRuZXqJ7ZkkcwNqBR_Kr6CES1iAeEpKfU5Z2on6ZCgK5IFu1cz4KlgQd4K-Hk4hSKEfBR7nwLp25R7dH4yrc_SdpzXVhatFE4QF61RPgD3A_JijIUTUsk-jS5a5oG9Zy9juSq-7bllU_y-_a0uwhcyzj8ulb5QJBAN2A8FgdEBzAn16WB1l0Szfymg8bYQk5QeCKUA_5scQsLP4g9XxqxehVXiN3Y40JMfEoj-C8hMVUEAmM1DNbb-cCQQC2Xwt4WnRotTVxxUWpxroQ9e6KpMnjEYPn6Zg336M9yTCRCQmceFQeYyYekIgn8bcDCUNKIAofz_pUl-ZbPFmPAkEAoKZfqsiJYxEhhUxy0CJUW6OMsOA-pJ3udZhbMPr8Pzd6-mWVJkOafkNMH5T7ktLUcf_lOi4Abc3mQ8bsMMNkiQJAQ1g7uxjkDdqEvtuTSwuIoETA7s_FgaVxKU24mUFrXaCS36wPsYk5vvLsG7NRpDZ9V5CvGYtVUcQSc_SX6y8Q_wJACtui3aQ3v_Ao1tJ8TMUG4r0GrOcW4dtqn2mnJOTgQNMKpQFyMJ2yirSd-oeN_hsKcSz1mY-kN_hE47Ll0EllKw";


    /**
     * 解密数据
     * @param requestApiParam
     * @return
     * @throws NoSuchAlgorithmException
     * @throws InvalidKeySpecException
     */
    public static String decode(RequestApiParam requestApiParam) throws NoSuchAlgorithmException, InvalidKeySpecException {
        //签名验证 通过appid以及时间戳验签
        boolean verify = RSAUtils.verify(RSAUtils.hexStringToBytes("" + requestApiParam.getServiceId() + requestApiParam.getTimestamp()),
                PUBLIC_KEY, requestApiParam.getSign());
        if (!verify) {
            throw new BaseException("签名验证失败");
        }
        //私钥解密，获取aseKey
        String aseKey2 = RSAUtils.privateDecrypt(requestApiParam.getAseKey(), RSAUtils.getPrivateKey(PRIVATE_KEY));
        if (!StringUtils.isEmpty(requestApiParam.getBody())) {
            try {
                // 解密请求报文
                return AESUtils.decode(aseKey2, requestApiParam.getBody());
            } catch (Exception e) {
                throw new BaseException("请求参数解密异常");
            }
        }
        return null;
    }
}
